import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/collection_model/first_publish_buy_order_model.dart';
import 'package:yysk_app/model/collection_model/first_publish_get_time_model.dart';
import 'package:yysk_app/model/collection_model/home_first_detail_model.dart';
import 'package:yysk_app/model/common_model/notice_list_model.dart';
import 'package:yysk_app/model/order_model/get_pay_token_model.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/api/order_api.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/order/order_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';

enum CollectionDetailType {
  first, // 首发
  userCollection, // 用户藏品
  market, // 市场藏品
  ip, // IP藏品
}

class CollectionDetailController extends GetxController {
  final isRead = false.obs;
  final buyNum = 1.obs;
  final maxNum = 1.obs;
  final price = 100.00;

  //显示购购买条件
  final showRule = false.obs;
  //显示优先购为 1 优先抢 为 2 ，公售为3
  final showType = "3".obs;
  int fristPage = 1;
  final pageSize = 10;
  late String collectionId;
  late String? marketType;

  final currentTab = 'detail'.obs;
  final amount = ''.obs;
  final type = ''.obs;
  final firstDetail = Rx<HomeFirstDetailModel?>(null);
  final firstPublishTime = Rx<FirstPublishGetTimeModel?>(null);

  late String? id;
  final showBuyButton = false.obs;
  Timer? _timer;

  //相关公告
  int pageNum = 1;
  final noticeList = RxList<NoticeListItem>();
  @override
  void onInit() {
    super.onInit();
    id = Get.parameters['id'] ?? Get.arguments['id'] ?? 0;
    getProductDetail().then((res) {
      getFirstPublishTime();
      getNoticeList();
    });
    firstPublishGetPrice();
    //4分钟
    final int min4 = 60 * 4;
    // 创建一个随机数生成器
    final random = Random();
    // 生成1到60之间的随机整数
    final int randomNumber = random.nextInt(60) + 1;

    //定时器
    _timer = Timer.periodic(Duration(seconds: (min4 + randomNumber)), (timer) {
      consoleLog('定时器=====走${(min4 + randomNumber)}');
      getFirstPublishTime();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
    consoleLog('消除了');
  }

  void add() {
    if (buyNum.value < maxNum.value) {
      buyNum.value++;
      firstPublishGetPrice();
    }
    consoleLog('${maxNum.value}===maxNum');
  }

  void subtract() {
    if (buyNum.value > 1) {
      buyNum.value--;
      firstPublishGetPrice();
    }
  }

  void max() {
    buyNum.value = maxNum.value;
    firstPublishGetPrice();
  }

  // FirstPublishGetTimeModel
  // 获取首发时间
  getFirstPublishTime() {
    http.netFetch<FirstPublishGetTimeModel>(
      '${ProductApi.firstPublishTime}/$id',
      method: Method.get,
      // params: {'count': buyNum.value, 'activityId': firstDetail.value?.id},
      success: (r) {
        firstPublishTime.value = r.data;
      },
    );
  }
  // 获取用户藏品详情

  Future<void> getProductDetail({loadMore = false}) {
    return http.netFetch<HomeFirstDetailModel>(
      '${ProductApi.firstPublish}/$id',
      method: Method.get,
      params: {'id': id},
      success: (result) {
        firstDetail.value = result.data;
        maxNum.value = result.data?.userCanBuyCount ?? 0;
        consoleLog('${maxNum.value}===maxNum');
      },
    );
  }

  Future<void> firstPublishGetPrice() {
    return http.netFetch<dynamic>(
      ProductApi.firstPublishGetPrice,
      method: Method.post,
      params: {'id': id, 'count': buyNum.value},
      success: (result) {
        amount.value = result.data['amount'];
      },
    );
  }

  // 创建首发订单
  createFirstOrder() {
    http.netFetch<FirstPublishBuyOrderModel>(
      OrderUrl.buyOrder,
      params: {'count': buyNum.value, 'activityId': firstDetail.value?.id},
      success: (r) {
        if (r.code == 200 && r.data!.noPay == false) {
          getPayToken(r.data!.orderId);
        } else {
          _toPayWaitOrder(context: Get.context!, res: r.data!);
        }
      },
    );
  }

  //去实名
  toSm({required BuildContext context}) async {
    await showConfirmDialog(
      context: context,
      message: '请先完成实名认证',
      messages: [],
      fontSize: 16,
      actions: [
        ActionModel(
          label: '取消',
          onPressed: () {},
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
        ),
        ActionModel(
          label: '立即认证',
          onPressed: () {
            Get.toNamed(SettingRealNameAuthPage.path);
          },
        ),
      ],
    );
  }

  //待支付订单
  _toPayWaitOrder({
    required BuildContext context,
    required FirstPublishBuyOrderModel res,
  }) async {
    await showConfirmDialog(
      context: context,
      message: '无法下单,您有未支付订单待处理',
      messages: [],
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即处理',
          onPressed: () {
            Get.toNamed(
              '${OrderPage.path}?productType=${res.productType}',
              arguments: {'productType': res.productType},
            );
          },
        ),
      ],
    );
  }

  //获取令牌
  Future<dynamic> getPayToken(dynamic sn) async {
    try {
      http.netFetch<GetPayTokenModel>(
        OrderUrl.getPayToken,
        method: Method.post,
        params: {"businessType": firstDetail.value?.productType, 'orderId': sn},
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=DEBUT&clientType=web&buynow=1',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'DEBUT',
              'buynow': '1',
            },
          );
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }

  //相关公告
  //获取notice公告数据
  Future<void> getNoticeList({loadMore = false, id = 0}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      return http.netFetch<NoticeListModel>(
        CommonApi.noticeList,
        method: Method.post,
        params: {
          'pageNum': pageNum,
          'pageSize': 100,
          "collectionId": firstDetail.value?.sourceId,
        },
        success: (result) {
          List<NoticeListItem> items = result.data?.list ?? [];

          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            noticeList.clear();
          }
          noticeList.addAll(items);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
      return Future.error(e);
    }
  }
}
